import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { LoginForm, ProConfigProvider, ProFormText } from '@ant-design/pro-components';
import { theme } from 'antd';
import useRoute from '@/hooks/useRoute';
import './index.less';
import { loginApi } from '@/api';
import { isLocal, isSuccess } from '@/utils';
import { useEffect, useRef } from 'react';
import store from 'storejs';

export default function Login() {
  const { goto } = useRoute();
  const { token } = theme.useToken();
  const formRef: any = useRef('');

  useEffect(() => {
    if (!isLocal()) return;
    formRef?.current?.setFieldsValue({
      username: 'admin',
      password: 'hd#admin',
    });
  }, []);

  // 登录
  async function submitApi(values: any) {
    const { username, password } = values;
    const params = { name: username, password };
    console.log('params: ', params);
    const res: any = await loginApi(params);
    console.log('登录-res: ', res);
    if (isSuccess(res)) {
      store.set('token', res?.data?.token);
      store.set('userInfo', res?.data?.userInfo);
      goto('/home');
    }
  }

  return (
    <div className="loginpage">
      <ProConfigProvider hashed={false}>
        <div style={{ backgroundColor: token.colorBgContainer }}>
          <LoginForm
            // logo="https://github.githubassets.com/favicons/favicon.png"
            formRef={formRef}
            title="管理后台"
            subTitle={'welcome '}
            onFinish={async (values) => submitApi(values)}
          >
            <ProFormText
              name="username"
              fieldProps={{
                size: 'large',
                prefix: <UserOutlined className={'prefixI con'} />,
              }}
              placeholder={'用户名'}
              rules={[
                {
                  required: true,
                  message: '请输入用户名!',
                },
              ]}
            />
            <ProFormText.Password
              name="password"
              fieldProps={{
                size: 'large',
                prefix: <LockOutlined className={'prefixIcon'} />,
              }}
              placeholder={'密码'}
              rules={[
                {
                  required: true,
                  message: '请输入密码！',
                },
              ]}
            />
          </LoginForm>
        </div>
      </ProConfigProvider>
    </div>
  );
}
